package com.xlh.Utils;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.xlh.interf.IOnClickListener;
import com.xlh.outside.MainActivity;

import org.apache.commons.lang3.ArrayUtils;
import org.xml.sax.XMLReader;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by fang on 2017-11-10.
 */

    public class FontHandler implements Html.TagHandler {
    private static final String TAG = "wzfont";

    private int startIndex = 0;
    private int stopIndex = 0;

    private final Context mContext;
    private String cmds;



    public IOnClickListener getClickListener() {
        return clickListener;
    }

    public void setClickListener(IOnClickListener clickListener) {
        this.clickListener = clickListener;
    }

    private IOnClickListener clickListener;

    public FontHandler(Context context){
        mContext=context;
    }
    public FontHandler builder(){
        return this;
    }

    final HashMap<String, String> attributes = new HashMap<String, String>();

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        processAttributes(xmlReader);

        if(tag.equalsIgnoreCase(TAG)){
                if(opening){
                    startIndex = output.length();
                }else{
                    endFont(tag, output, xmlReader);
                }
        }
    }

    public void startFont(String tag, Editable output, XMLReader xmlReader) {
        startIndex = output.length();
    }


    private String[] styleList = new String[]{"color","size","cmds","background"};


    public void endFont(String tag, Editable output, XMLReader xmlReader){
        stopIndex = output.length();
        String color,size,cmds,background,style,tAry[],tSary[],tStr;
        color    = attributes.get("color");
        size     = attributes.get("size");
        cmds     = attributes.get("cmds");
        background     = attributes.get("background");
        style = attributes.get("style");
        // size = size.split("px")[0];

        //if(!TextUtils.isEmpty(color) && !TextUtils.isEmpty(size)){//
           // if(!TextUtils.isEmpty(size)){
              //  output.setSpan(new AbsoluteSizeSpan(Integer.parseInt(size)), startIndex, stopIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
           // }

        //分析style
        if(style.indexOf(";")>-1){
            //如果有;表示多个属性
            tAry = style.split(";");
            for(String s : tAry){
                tSary = s.split(":");
                tStr = tSary[0];

                if( tStr.equals("color") && !tSary[1].isEmpty() && !tSary[1].equals("undefined") ){
                    color = tSary[1];
                }else if(tStr.equals("size") && !tSary[1].isEmpty() && !tSary[1].equals("undefined")){
                    size = tSary[1];
                }else if(tStr.equals("cmds") && !tSary[1].isEmpty() && !tSary[1].equals("undefined")){
                    cmds = tSary[1];
                }else if(tStr.equals("background") && !tSary[1].isEmpty() && !tSary[1].equals("undefined")){
                    background = tSary[1];
                }else{
                    break;
                }
            }


        }else{
            tAry = style.split(":");
           // ArrayUtils.indexOf(styleList, tAry[0] );
            tStr = tAry[0];

            if( tStr.equals("color") && !tAry[1].isEmpty() && !tAry[1].equals("undefined")){
                color = tAry[1];
            }else if(tStr.equals("size") && !tAry[1].isEmpty() && !tAry[1].equals("undefined")){
                size = tAry[1];
            }else if(tStr.equals("cmds") &&  !tAry[1].isEmpty() && !tAry[1].equals("undefined")){
                cmds = tAry[1];
            }else if(tStr.equals("background") &&  !tAry[1].isEmpty() && !tAry[1].equals("undefined")){
                background = tAry[1];
            }else{
                return;
            }

        }


        if (size!=null && !size.isEmpty()){
            output.setSpan(new AbsoluteSizeSpan(FUti.dip2px(mContext,Integer.parseInt(size))), startIndex, stopIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (color!=null && !color.isEmpty()){
            output.setSpan(new ForegroundColorSpan(Color.parseColor(color)), startIndex, stopIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


        if (background!=null && !background.isEmpty()){
            //创建BackgroundColorSpan对象，指定背景色为黄色
            BackgroundColorSpan backgroundColorSpan=new BackgroundColorSpan(Color.parseColor(background));
            //使用setSpan方法将指定字符串转换成BackgroundColorSpan对象
            output.setSpan(backgroundColorSpan, startIndex, stopIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if(cmds!=null && !cmds.isEmpty()){
            output.setSpan(new onClickSpan(cmds), startIndex, stopIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }








    }


    private class onClickSpan extends ClickableSpan implements OnClickListener{



        private String cmds;

        public String getCmds() {
            return cmds;
        }

        public void setCmds(String cmds) {
            this.cmds = cmds;
        }

        public onClickSpan(String cmd){
            super();
            this.setCmds(cmd);
        }

        @Override
        public void onClick(View widget) {
                // TODO Auto-generated method stub

                //具体代码，可以是跳转页面，可以是弹出对话框，下
                // mContext.startActivity(new Intent(mContext,MainActiv面是跳转页面ity.class));
                if (this.cmds.isEmpty()){
                    Toast tst = Toast.makeText(mContext, "点击标签指令为空！", Toast.LENGTH_SHORT);
                    tst.setGravity(Gravity.TOP, 0, 100);
                    tst.show();
                    return;
            }

            //如果定义了外部点击接口
            if (clickListener!=null){
                clickListener.onClick(cmds);
            }

            ((MainActivity)mContext).getmSocketClient().sendMsg(cmds);


        }
    }

    /**
     * by  fang/大当家/QQ184377367
     * xmlReader 结构是传入的HTML的结构
     * 该函数主要实现解析出HTML中的节点属性
     * @param xmlReader
     */
    private void processAttributes(final XMLReader xmlReader) {
        try {
            Field elementField = xmlReader.getClass().getDeclaredField("theNewElement");
            elementField.setAccessible(true);
            Object element = elementField.get(xmlReader);
            Field attsField = element.getClass().getDeclaredField("theAtts");
            attsField.setAccessible(true);
            Object atts = attsField.get(element);
            Field dataField = atts.getClass().getDeclaredField("data");
            dataField.setAccessible(true);
            String[] data = (String[])dataField.get(atts);
            Field lengthField = atts.getClass().getDeclaredField("length");
            lengthField.setAccessible(true);
            int len = (Integer)lengthField.get(atts);

            for(int i = 0; i < len; i++){
                attributes.put(data[i * 5 + 1], data[i * 5 + 4]);
            }
        }
        catch (Exception e) {

        }
    }




}